package com.example.zbh.dsliao.ui.activty;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zbh.dsliao.MusicIdle;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.model.entity.LocalMusic;
import com.example.zbh.dsliao.service.MyService;
import com.example.zbh.dsliao.ui.adapter.LocalMusicListViewAdapter;
import com.example.zbh.dsliao.utils.FormatTime;
import com.example.zbh.dsliao.utils.MyEventBus;
import com.example.zbh.dsliao.utils.FindSongs;
import com.example.zbh.dsliao.utils.MyConfig;

import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by yaolin on 15/11/19.
 */

public class LocalActivity extends Activity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {

    private ImageView img_back;     //back键
    private ListView mListView;     //列表
    public TextView music_artist, music_duration;    //歌名 歌手  时长
    public ImageView music_album, img_previous, img_play, img_next, img_select;  //  专辑图片  上一首 播放  下一首  选择
    private TextView progressTv, maxTv;

    private SeekBar progress;//定义一个进度条
    private List<LocalMusic> localMusics;
    private LocalMusic localMusic;
    private FindSongs finder;
    private String singer;
    private String song;
    private String songsUrl;


    private LocalMusicListViewAdapter adapter;   //适配器
    private int currentPosition;                 //当前位置
    private MusicIdle mService;
    //上下文
    private Context context;
    //连接对象
    private ServiceConnection conn = new ServiceConnection() {

        /**
         * 当绑定服务成功之后会回调的方法,需要记录一下IBinder对象
         * @param name
         * @param service
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = MusicIdle.Stub.asInterface(service);
            try {
                if (!mService.getMusicIsPlaying() && MyService.getMax()  > MyService.getProgress()) {
                    // pauseBtn.setText("播放");
                    img_play.setImageResource(R.mipmap.deep_play_btn);
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }
    };

    private Intent intent;
    private int progess;
    private int max;





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local);

        initView();
        initData();
        click();
    }


    /**初始化组件**/
    private void initView() {
        img_back = (ImageView) findViewById(R.id.img_back);
        mListView = (ListView) findViewById(R.id.listview);
        music_album = (ImageView) findViewById(R.id.music_album);
        img_play = (ImageView) findViewById(R.id.img_play);
        img_previous = (ImageView) findViewById(R.id.img_previous);
        img_next = (ImageView) findViewById(R.id.img_next);
        progress = (SeekBar) findViewById(R.id.progress);

        //播放时间
        progressTv = (TextView) findViewById(R.id.tv_time_progress);
        maxTv = (TextView) findViewById(R.id.tv_time_max);

        music_artist = (TextView) findViewById(R.id.song);
    }


    /**
     * 组件的监听事件
     * **/
    private void click() {
        img_play.setOnClickListener(this);
        // stopBtn.setOnClickListener(this);
        // pauseBtn.setOnClickListener(this);
        img_previous.setOnClickListener(this);
        img_next.setOnClickListener(this);
        progress.setOnSeekBarChangeListener(this);
        img_back.setOnClickListener(this);
    }






    /**
     * 设置数据
     * */
    private void initData() {

        //在要接收消息的页面注册eventBus
        EventBus.getDefault().register(this);


        //绑定服务
        intent = new Intent(this, MyService.class);
        this.startService(intent);
        this.bindService(intent, conn, BIND_AUTO_CREATE);


        //设置数据
        finder = new FindSongs();
        localMusics = finder.getMp3Infos(getContentResolver());
        adapter = new LocalMusicListViewAdapter(this, localMusics);
        finder.setListAdpter(context, localMusics, mListView);
        //发送消息
        EventBus.getDefault().post(new MyEventBus.MusicDatas(localMusics));

        /**
         * listview行布局监听
         */
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                localMusic = (LocalMusic) parent.getItemAtPosition(position);

                Log.i("MainActivity", "mp3Info" + localMusic.getUrl());
                songsUrl = localMusic.getUrl();
                singer = localMusic.getArtist();
                song = localMusic.getTitle();
                Log.i("TestActivity", "songsUrl" + songsUrl);
                currentPosition = position;
                EventBus.getDefault().post(new MyEventBus.CurrentIndex(currentPosition));
                MyConfig.putSharePre(LocalActivity.this, "text", "songsName", song);
                MyConfig.putSharePre(LocalActivity.this, "text", "singerName", singer);
                play();
                img_play.setImageResource(R.mipmap.deep_pause_btn);
                maxTv.setText(String.valueOf(FormatTime.formatTime(localMusic.getDuration())));

                try {
                    progress.setMax(mService.getDuration());
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

        EventBus.getDefault().post(new MyEventBus.ActivityCreate(1));
    }






    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_play:
                pause();
                break;
            case R.id.img_previous:
                previous();
                img_play.setImageResource(R.mipmap.deep_pause_btn);
                break;
            case R.id.img_next:
                next();
                img_play.setImageResource(R.mipmap.deep_pause_btn);
                break;
            case R.id.img_back:     //后退
                finish();
                break;
        }
    }

    /**
     * 播放
     * **/
    private void play() {
        if (mService != null && localMusics.size() > 0) {
            try {
                music_artist.setText(song  +  "  "  + singer);
                if (songsUrl != null && songsUrl != "") {
                    mService.setUrl(songsUrl);
                } else {
                    Toast.makeText(this, "当前没有歌曲可以播放", Toast.LENGTH_SHORT).show();
                }
                if (mService.getMusicIsPlaying()) {
                    //   pauseBtn.setText("暂停");
                    img_play.setImageResource(R.mipmap.deep_pause_btn);
                }
                mService.play();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(this, "当前没有歌曲可以播放", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 停止
     * **/
    private void stop() {
        if (mService != null) {
            try {
                mService.stop();
                //解绑
                finish();
                stopService(intent);
                mService = null;
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 暂停
     * **/
    private void pause() {
        if (mService != null ) {
            try {
                if (mService.getMusicIsPlaying()) {
                    img_play.setImageResource(R.mipmap.deep_play_btn);//.setText("播放");
                    mService.pause();
                } else  {
                    img_play.setImageResource(R.mipmap.deep_pause_btn);// pauseBtn.setText("暂停");
                    mService.play();
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 上一首
     * **/
    private void previous() {
        if (mService != null) {
            try {
                mService.previous();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 下一首
     * **/
    private void next() {
        if (mService != null) {
            try {
                mService.next();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (mService != null) {
            try {
                //获得滑块当前的进度
                int position = seekBar.getProgress();
                //设置音乐播放的位置
                mService.setProgress(position);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 接受消息的页面实现(共有四个函数，各功能不同)
     * **/
    public void onEventMainThread(MyEventBus.UpDataSeek upDataSeek) {
        if(upDataSeek.getProgress() == 0){
            progress.setProgress(0);

        }else{
            progress.setProgress(upDataSeek.getProgress());

            progressTv.setText(FormatTime.formatTime((long) upDataSeek.getProgress()));
        }

    }

    public void onEventMainThread(MyEventBus.SeekBarMax seedMax) {
        if (seedMax.getMax() == 0){
            progress.setMax(100);
        }else{
            progress.setMax(seedMax.getMax());
        }
    }



    public void onEventMainThread(MyEventBus.SingerName singerName) {
        music_artist.setText(singerName.getName());
        Log.i("what", "singerName" + singerName.getName());
        MyConfig.putSharePre(this, "text", "singerName", singerName.getName());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //解绑服务
        unbindService(conn);
        stopService(intent);
        //解除注册
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        song = MyConfig.getSharePreStr(this, "text", "songsName");
        singer = MyConfig.getSharePreStr(this, "text", "singerName");
        if (song != null && song != "" && singer != null && singer != "") {
            music_artist.setText(song + "       " + singer);
        }
    }


}
